package com.sdust.controller;

import com.sdust.model.Book;
import com.sdust.utils.jdbcUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/book/add")
public class AddBookController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String name = req.getParameter("name");
        String author = req.getParameter("author");
        String price = req.getParameter("price");
        String publisher = req.getParameter("publisher");
        String publishDate = req.getParameter("publishDate");

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        LocalDateTime publishDate_format = LocalDateTime.parse(publishDate + "T00:00:00", formatter);

        Book book = new Book(name, author, Double.parseDouble(price), publisher, publishDate_format);
        try {
            jdbcUtils.addBook(book);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 转发到获取全部书籍的Servlet
        RequestDispatcher dispatcher = req.getRequestDispatcher("/book/books");
        dispatcher.forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
